package com.hcm.module.gzfk.data;

import com.hcm.module.gzfk.model.Goods;
import com.hcm.module.gzfk.service.IGoodsService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

/**
 * 获取数据
 */
public class FetchDataUtil {

    public static List<Goods> getData(String url,String cookie,IGoodsService goodsService){
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet get = new HttpGet(url);
//        get.addHeader(new BasicHeader("Cookie", cookie));
        get.addHeader("Content-Type", "text/html;charset=UTF-8");
        get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0");
        get.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        get.addHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(
                    final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                System.out.println(status);
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }

        };

        try {
            String responseBodyx = httpClient.execute(get, responseHandler);
            ParseHtml parseHtml = new ParseHtml();
            return parseHtml.get(responseBodyx,goodsService);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
